package org.gwu.seuss;

import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.gwu.seuss.communication.sockets.ssl.Util;
import org.gwu.seuss.communication.util.PasswordPrompt;
import org.gwu.seuss.server.SeussServer;
import org.gwu.seuss.server.SeussServerFactory;
import org.gwu.seuss.service.ServiceFactory;

public class App {
	private static final String CONNECTION_PROPERTIES = "connection.properties";
	private static final String SSL_PORT = "ssl.port";
	static Logger log = Logger.getLogger(App.class);

	public static void main(String[] args) {

		SeussServer ss = null;
		char[] storePassword = null;

		try {
			Properties connectionProps=  Util
						.loadPropertiesFromResource(CONNECTION_PROPERTIES);
			storePassword = PasswordPrompt
					.askForPassword("Please enter store password");
			ss = SeussServerFactory.createSslServer(storePassword,
					Integer.parseInt(connectionProps.getProperty(SSL_PORT)));
		} catch (Exception ex) {
			log.error("Failed to create ssl server", ex);
		} finally {

			if (storePassword != null) {
				Arrays.fill(storePassword, ' ');
			}
		}

		try {
			ServiceFactory.initDataBaseService();
		} catch (Exception ex) {
			log.error("Failed to initialize database service", ex);
		}

		if (ss != null) {

			log.info("Starting seuss server. Listening on port " + ss.getPort());

			try {
				ss.start();
			} catch (IOException e) {
				log.error("Failed to startup the Seuss Server", e);
			}
		}
	}
}
